package com.self.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.self.serviceedu.entity.EduSubject;
import com.self.serviceedu.entity.excel.SubjectData;
import com.self.serviceedu.entity.subject.OneSubject;
import com.self.serviceedu.entity.subject.TwoSubject;
import com.self.serviceedu.listener.SubjectExcelListener;
import com.self.serviceedu.mapper.EduSubjectMapper;
import com.self.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.management.Query;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author xiaozeng
 * @since 2020-09-12
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {

        try {
            InputStream inputStream = file.getInputStream();

            EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //课程分类列表
    @Override
    public List<OneSubject> getAllOneTwoSubject() {

        //1.查询所有一级分类
        QueryWrapper<EduSubject> oneWrapper = new QueryWrapper<>();
        oneWrapper.eq("parent_id",0);
        List<EduSubject> OneSubjects = baseMapper.selectList(oneWrapper);

        //2.查询所有的二级分类
        QueryWrapper<EduSubject> twoWrapper = new QueryWrapper<>();
        twoWrapper.ne("parent_id",0);
        List<EduSubject> twoSubjects = baseMapper.selectList(twoWrapper);

        ArrayList<OneSubject> finalSubjectList = new ArrayList<>();

        //3. 封装一级分类
        for (EduSubject eduSubject1 : OneSubjects) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject1,oneSubject);
            finalSubjectList.add(oneSubject);

            ArrayList<TwoSubject> twoFinalSubjectList = new ArrayList<>();
            //4. 封装二级分类
            for (EduSubject tSubject : twoSubjects) {
                if(tSubject.getParentId().equals(oneSubject.getId())){
                    //把tSubject值复制到TwoSubject里面，放到twoFinalList里面
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject);
                    twoFinalSubjectList.add(twoSubject);
                }

            }
            //将所有二级分类放到一级分类里面
            oneSubject.setChildren(twoFinalSubjectList);
        }



        return finalSubjectList;
    }
}
